//
//  AppDelegate.m
//  CYLTabBarController
//


#import "AppDelegate.h"

#import "AILoginVc.h"
#import "QDNavigationController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "AuthSignin_model.h"

#import "JPUSHService.h"

#import <AdSupport/AdSupport.h>

#import <CoreLocation/CoreLocation.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "ESP_NetUtil.h"

#import "QDTabBarViewController.h"



#import "QMUIConfigurationTemplateDark.h"

#import "CYLHomeViewController.h"

#import "CYLMineViewController.h"
#import "QDNavigationController.h"
#import "GailanPagerVc.h"
#import "Faxian_vc.h"

//友盟分享
#import <UMShare/UMShare.h>

#import <UMCommon/UMCommon.h>

#import <UIViewController+Swizzled.h>
#define LOGTAG @"调试👌:进入"
#import "YTKNetworkConfig.h"

// 缓存歌曲
#import "GetMusicReq.h"
#import "GetMusic_category_list.h"
#import "MusicCategory.h"

@interface AppDelegate ()<JPUSHRegisterDelegate,JPUSHGeofenceDelegate>{
    CLLocationManager * _locationManager;
    
}
@property (nonatomic, strong) NSMutableData *data;



@end

@implementation AppDelegate
#pragma mark - ================== qmui start ==================
- (void)didInitWindow {
    self.window.rootViewController = [self generateWindowRootViewController];
    [self.window makeKeyAndVisible];
    
    
    
    
}

- (UIViewController *)generateWindowRootViewController {
    QDTabBarViewController *tabBarViewController = [[QDTabBarViewController alloc] init];
    

    GailanPagerVc *gailan_vc = [[GailanPagerVc alloc] init];
    gailan_vc.navigationBarHidden = YES;
    gailan_vc.hidesBottomBarWhenPushed = NO;

    QDNavigationController *gailan_navi = [[QDNavigationController alloc]
                                     initWithRootViewController:gailan_vc];

    
    gailan_navi.tabBarItem = [QDUIHelper tabBarItemWithTitle:@"首页" image:UIImageMake(@"main_icon") selectedImage:UIImageMake(@"main_selected_icon") tag:0];
    
    

    
    CYLHomeViewController *zhineng_ViewController = [[CYLHomeViewController alloc] init];
    zhineng_ViewController.hidesBottomBarWhenPushed = NO;
    zhineng_ViewController.navigationBarHidden = YES;
    QDNavigationController *zhineng_navi = [[QDNavigationController alloc]
                                      initWithRootViewController:zhineng_ViewController];
    zhineng_navi.tabBarItem = [QDUIHelper tabBarItemWithTitle:@"智能" image:UIImageMake(@"capacity_icon") selectedImage:UIImageMake(@"capacity_selected_icon") tag:1];

    
    Faxian_vc *faxian_vc = [[Faxian_vc alloc] init];
    faxian_vc.hidesBottomBarWhenPushed = NO;
    QDNavigationController *faxian_navi = [[QDNavigationController alloc]
                                     initWithRootViewController:faxian_vc];
    faxian_navi.tabBarItem = [QDUIHelper tabBarItemWithTitle:@"发现" image:UIImageMake(@"found_icon") selectedImage:UIImageMake(@"found_selected_icon") tag:2];

    
    CYLMineViewController *wode_vc = [[CYLMineViewController alloc] init];
    wode_vc.hidesBottomBarWhenPushed = NO;

    QDNavigationController *wode_navi = [[QDNavigationController alloc]
                                   initWithRootViewController:wode_vc];
    
    wode_navi.tabBarItem = [QDUIHelper tabBarItemWithTitle:@"我的" image:UIImageMake(@"mine_icon") selectedImage:UIImageMake(@"mine_selected_icon") tag:3];
    
    
    // window root controller
    tabBarViewController.viewControllers = @[gailan_navi, zhineng_navi, faxian_navi, wode_navi];
    return tabBarViewController;
}

- (void)handleThemeDidChangeNotification:(NSNotification *)notification {
    
    QMUIThemeManager *manager = notification.object;
    if (![manager.name isEqual:QMUIThemeManagerNameDefault]) return;
    
    [[NSUserDefaults standardUserDefaults] setObject:manager.currentThemeIdentifier forKey:QDSelectedThemeIdentifier];
    
    [QDThemeManager.currentTheme applyConfigurationTemplate];
    
    // 主题发生变化，在这里更新全局 UI 控件的 appearance
    [QDCommonUI renderGlobalAppearances];
    
    // 更新表情 icon 的颜色
    [QDUIHelper updateEmotionImages];
}


#pragma mark - ================== qmui end ==================

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    // 1. 先注册主题监听，在回调里将主题持久化存储，避免启动过程中主题发生变化时读取到错误的值
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleThemeDidChangeNotification:) name:QMUIThemeDidChangeNotification object:nil];

    // 2. 然后设置主题的生成器
    QMUIThemeManagerCenter.defaultThemeManager.themeGenerator = ^__kindof NSObject * _Nonnull(NSString * _Nonnull identifier) {
        if ([identifier isEqualToString:QDThemeIdentifierDefault]) return QMUIConfigurationTemplate.new;
        if ([identifier isEqualToString:QDThemeIdentifierDark]) return QMUIConfigurationTemplateDark.new;
        

        return nil;
    };
    
    

    // 3. 再针对 iOS 13 开启自动响应系统的 Dark Mode 切换
    // 如果不需要这个功能，则不需要这一段代码
    if (@available(iOS 13.0, *)) {
        // 做这个 if(currentThemeIdentifier) 的保护只是为了避免 QD 里的配置表没启动时，没人为 currentTheme/currentThemeIdentifier 赋值，导致后续的逻辑会 crash，业务项目里理论上不会有这种情况出现，所以可以省略这个 if 块
        if (QMUIThemeManagerCenter.defaultThemeManager.currentThemeIdentifier) {
            QMUIThemeManagerCenter.defaultThemeManager.identifierForTrait = ^__kindof NSObject<NSCopying> * _Nonnull(UITraitCollection * _Nonnull trait) {
                if (trait.userInterfaceStyle == UIUserInterfaceStyleDark) {
                    return QDThemeIdentifierDark;
                }
                
                if ([QMUIThemeManagerCenter.defaultThemeManager.currentThemeIdentifier isEqual:QDThemeIdentifierDark]) {
                    return QDThemeIdentifierDefault;
                }
                
                return QMUIThemeManagerCenter.defaultThemeManager.currentThemeIdentifier;
            };
            QMUIThemeManagerCenter.defaultThemeManager.respondsSystemStyleAutomatically = YES;
        }
    }
    // QMUIConsole 默认只在 DEBUG 下会显示，作为 Demo，改为不管什么环境都允许显示
    [QMUIConsole sharedInstance].canShow = YES;
    
    // QD自定义的全局样式渲染
    [QDCommonUI renderGlobalAppearances];
    
    
    // 界面
    self.window = [[UIWindow alloc] init];
    
    
    [self handleKeyboard];
    
    // 是否登录 
    NSString *login_info = [[NSUserDefaults standardUserDefaults] objectForKey:@"login_or_not"];
    if ([Anktool strIsBlank:login_info]) {
        // 没有登录过才有可能有引导页
        [self ank_switch_to_loginVc];
    }else{
        
        NSString *jsonStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"ank_sign"];
        
        AuthSignin_model *signin = [AuthSignin_model mj_objectWithKeyValues:jsonStr];
        DLog(@"%@", signin.data.user_info.user_name);
        
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:app_code forKey:@"appCode"];
        [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
        
        
        
        
        
        [PPHTTPRequest req:@"java/app/user/getUserInfo" parameters:dict success:^(id response) {
            NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
            if ([error_code isEqualToString:@"0"]) {
                /*
                {
                    "error_msg": "操作成功",
                    "data": {
                        "userId": 113,
                        "nickName": "15979836292",
                        "avatarUrl": "",
                        "mobile": null
                    },
                    "error_code": 0
                }
                */
                NSDictionary *data_dic = response[@"data"];
                NSString *nickName = [NSString stringWithFormat:@"%@", data_dic[@"nickName"]];
                NSString *avatarUrl = [NSString stringWithFormat:@"%@", data_dic[@"avatarUrl"]];
                NSString *mobile = [NSString stringWithFormat:@"%@", data_dic[@"mobile"]];
                AuthSignin_model.sharedInstance.data.user_info.avatar_url = avatarUrl;
                AuthSignin_model.sharedInstance.data.user_info.nick_name = nickName;
                AuthSignin_model.sharedInstance.data.user_info.mobile = mobile;
                NSString *dictStr = [AuthSignin_model.sharedInstance mj_JSONString];
                [[NSUserDefaults standardUserDefaults] setObject:dictStr forKey:@"ank_sign"];
                
                
                
                
            }
            else{
                
                
                DLog(@"%@", response[@"error_msg"]);
                
            }
            
        } failure:^(NSError *error) {
            DLog(@"%@", [error localizedDescription]);
            
        }];
        
        
        [self ank_switch_to_tab];
        
        
        
    }
    
//

#ifdef DEBUG
    NSBundle *b = [[NSBundle alloc] initWithPath:@"/Applications/InjectionIII.app/Contents/Resources/iOSInjection.bundle"];
    [b load];
    
#endif
    [self jpush_setupWithOptions:launchOptions];
    
    [ESP_NetUtil tryOpenNetworkPermission];

//    if (@available(iOS 13.0, *)) {
//        [self.window setOverrideUserInterfaceStyle:UIUserInterfaceStyleLight];
//    }
    
    [self configUSharePlatforms];
    
//    SWIZZ_IT_WITH_TAG(LOGTAG);

    NSString *base_url = @"http://www.ainankang.com";// 线上 http://www.ainankang.com
#ifdef DEBUG
    base_url = @"http://www.ainankang.com";// 测试 // 第二版改版测试地址 http://test2.ainankang.com
#else
    
#endif
    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    config.baseUrl = base_url;
    [self cache_music];

    return YES;
}


- (void)jpush_setupWithOptions:(NSDictionary *)launchOptions {
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // 3.0.0及以后版本注册
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        //    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        //      NSSet<UNNotificationCategory *> *categories;
        //      entity.categories = categories;
        //    }
        //    else {
        //      NSSet<UIUserNotificationCategory *> *categories;
        //      entity.categories = categories;
        //    }
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    //如果使用地理围栏，请先获取地理位置权限。
    [self getLocationAuthority];
    //如果使用地理围栏功能，需要注册地理围栏代理
    [JPUSHService registerLbsGeofenceDelegate:self withLaunchOptions:launchOptions];
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    

}
- (void)ank_switch_to_loginVc{
    AILoginVc *vc = [[AILoginVc alloc] init];
    vc.navigationBarHidden = YES;
    self.window.rootViewController = [[QDNavigationController alloc] initWithRootViewController:vc];
    [self.window makeKeyAndVisible];
}
- (void)ank_switch_to_tab{
    [self didInitWindow];
}
- (void)handleKeyboard{
    
    [IQKeyboardManager sharedManager].enable = YES;
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    [IQKeyboardManager.sharedManager setDisabledToolbarClasses:[[NSMutableSet alloc]initWithArray:@[NSClassFromString(@"Tiezi_pinglun_vc") , NSClassFromString(@"Tiezi_pinglun_erji_vc")]]];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate
    // timers, and store enough application state information to restore your
    // application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called
    // instead of applicationWillTerminate: when the user quits.
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    const unsigned int *tokenBytes = [deviceToken bytes];
    NSString *tokenString = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                             ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                             ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                             ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];

    NSLog(@"Device Token: %@", tokenString);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS6及以下系统，收到通知:%@", [self logDic:userInfo]);
//    [rootViewController addNotificationCount];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
    
    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
//        [rootViewController addNotificationCount];
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
        
//        [rootViewController addNotificationCount];
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
//        [rootViewController addNotificationCount];
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}

- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info {
    NSLog(@"receive notification authorization status:%lu, info:%@", status, info);
//    [self alertNotificationAuthorization:status];
}

/*
// 通知未授权时提示，是否进入系统设置允许通知，仅供参考
- (void)alertNotificationAuthorization:(JPAuthorizationStatus)status {
    
    if (status < JPAuthorizationStatusAuthorized) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"允许通知" message:@"只有打开通知才能收到提醒，是否进入设置允许通知？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [JPUSHService openSettingsForNotification:^(BOOL success) {
                           NSLog(@"open settings %@", success?@"success":@"failed");
                       }];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
*/
#endif

#ifdef __IPHONE_12_0
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification {
    NSString *title = nil;
    if (notification) {
        title = @"从通知界面直接进入应用";
    }else{
        title = @"从系统设置界面进入应用";
    }
    UIAlertView *test = [[UIAlertView alloc] initWithTitle:title
                                                   message:@"pushSetting"
                                                  delegate:self
                                         cancelButtonTitle:@"yes"
                                         otherButtonTitles:nil, nil];
    [test show];
    
}
#endif

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}
#pragma mark -JPUSHGeofenceDelegate
//进入地理围栏区域
- (void)jpushGeofenceIdentifer:(NSString *)geofenceId didEnterRegion:(NSDictionary *)userInfo error:(NSError *)error {
    NSLog(@"进入地理围栏区域");
    if (error) {
        NSLog(@"error = %@",error);
        return;
    }
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        [self testAlert:userInfo];
    }else{
        // 进入后台
        [self geofenceBackgroudTest:userInfo];
    }
}
//离开地理围栏区域
- (void)jpushGeofenceIdentifer:(NSString *)geofenceId didExitRegion:(NSDictionary *)userInfo error:(NSError *)error {
    NSLog(@"离开地理围栏区域");
    if (error) {
        NSLog(@"error = %@",error);
        return;
    }
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        [self testAlert:userInfo];
    }else{
        // 进入后台
        [self geofenceBackgroudTest:userInfo];
    }
}
//
- (void)geofenceBackgroudTest:(NSDictionary * _Nullable)userInfo{
    //静默推送：
    if(!userInfo){
        NSLog(@"静默推送的内容为空");
        return;
    }
    //TODO
    
}

- (void)testAlert:(NSDictionary*)userInfo{
    if(!userInfo){
        NSLog(@"messageDict 为 nil ");
        return;
    }
    NSString *title = userInfo[@"title"];
    NSString *body = userInfo[@"content"];
    if (title &&  body ) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:body delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }
}
#pragma mark location
- (void)getLocationAuthority{
    _locationManager= [[CLLocationManager alloc] init];
    if(@available(iOS 8.0, *)) {
        [_locationManager requestAlwaysAuthorization];
    }else{
        if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
            NSLog(@"kCLAuthorizationStatusNotDetermined");
        }
    }
    _locationManager.delegate = (id<CLLocationManagerDelegate>)self;
}
#pragma mark -CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status != kCLAuthorizationStatusNotDetermined) {
        NSLog(@"获取地理位置权限成功");
    }
}
#pragma mark - ================== 友盟 ==================
- (void)configUSharePlatforms
{
    //友盟分享
    //    [UMCommonLogManager setUpUMCommonLogManager];
    [UMConfigure setLogEnabled:YES];
    [UMConfigure initWithAppkey:@"5ec34e00978eea0825f4eedb" channel:@"App Store"];
    
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx8e26ae87637454c6" appSecret:@"6cb1ed41d4652c274a29fdea366ca82e" redirectURL:@"http://mobile.umeng.com/social"];
    //     [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx06a25f184eb235f1" appSecret:@"7a1e314843cfa0d9f6ac3df6b5441a2c" redirectURL:@"http://mobile.umeng.com/social"];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    //    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"101506596"/*设置QQ平台的appID*/  appSecret:nil redirectURL:@"http://mobile.umeng.com/social"];
    
}

#pragma mark - ================== 缓存歌曲的请求 ==================
- (void)cache_music{
    
    GetMusicReq *api =[[GetMusicReq alloc] init];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        // 你可以直接在这里使用 self
        NSLog(@"succeed");
        
        MusicCategory *musicCategory = [MusicCategory mj_objectWithKeyValues:request.responseJSONObject];
        
        for (MusicCategoryData *ac in musicCategory.data) {
            GetMusic_category_list *req = [[GetMusic_category_list alloc] init_page:@"1" page_size:@"100" category_id:@(ac.ID).stringValue];
            [req startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                
            } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                
            }];
            
        }
        
        
    } failure:^(YTKBaseRequest *request) {
        // 你可以直接在这里使用 self
        NSLog(@"failed");
    }];
}
@end
